/*
 * Copyright (C) 2016 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.internal.platform;
import okhttp3.Protocol;
import okhttp3.internal.Util;
import okhttp3.internal.tls.CertificateChainCleaner;
import okhttp3.internal.tls.TrustRootIndex;
import javax.annotation.Nullable;
import javax.net.ssl.*;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * Harmony 5+.
 */
public class OhosPlatform extends Platform {
    private static final int MAX_LOG_LENGTH = 4000;

    private final Class<?> sslParametersClass;
    private final Class<?> sslSocketClass;
    private final Method setUseSessionTickets;
    private final Method setHostname;
    private final Method getAlpnSelectedProtocol;
    private final Method setAlpnProtocols;

    private final CloseGuard closeGuard = CloseGuard.get();

    OhosPlatform(Class<?> sslParametersClass, Class<?> sslSocketClass, Method setUseSessionTickets,
                 Method setHostname, Method getAlpnSelectedProtocol, Method setAlpnProtocols) {
        this.sslParametersClass = sslParametersClass;
        this.sslSocketClass = sslSocketClass;
        this.setUseSessionTickets = setUseSessionTickets;
        this.setHostname = setHostname;
        this.getAlpnSelectedProtocol = getAlpnSelectedProtocol;
        this.setAlpnProtocols = setAlpnProtocols;
    }

    @Override
    public void connectSocket(Socket socket, InetSocketAddress address,
                              int connectTimeout) throws IOException {
        try {
            socket.connect(address, connectTimeout);
        } catch (AssertionError mAssert) {
            if (Util.isOhosGetsocknameError(mAssert)) {
                throw new IOException(mAssert);
            }
            throw mAssert;
        } catch (ClassCastException classCastException) {
            throw classCastException;
        }
    }

    @Override
    protected @Nullable
    X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
        Object context = readFieldOrNull(sslSocketFactory, sslParametersClass, "sslParameters");
        if (context == null) {
            // must be loaded by the SSLSocketFactory's class loader.
            try {
                Class<?> gmsSslParametersClass = Class.forName(
                        "com.google.android.gms.org.conscrypt.SSLParametersImpl", false,
                        sslSocketFactory.getClass().getClassLoader());
                context = readFieldOrNull(sslSocketFactory, gmsSslParametersClass, "sslParameters");
            } catch (ClassNotFoundException e) {
                return super.trustManager(sslSocketFactory);
            }
        }

        X509TrustManager x509TrustManager = readFieldOrNull(
                context, X509TrustManager.class, "x509TrustManager");
        if (x509TrustManager != null) {
            return x509TrustManager;
        }

        return readFieldOrNull(context, X509TrustManager.class, "trustManager");
    }

    @Override
    public void configureTlsExtensions(
            SSLSocket sslSocket, String hostname, List<Protocol> protocols) throws IOException {
        if (!sslSocketClass.isInstance(sslSocket)) {
            return;
        }
        try {
            if (hostname != null) {
                setUseSessionTickets.invoke(sslSocket, true);
                setHostname.invoke(sslSocket, hostname);
            }
            setAlpnProtocols.invoke(sslSocket, concatLengthPrefixed(protocols));
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new AssertionError(e);
        }
    }

    @Override
    public @Nullable
    String getSelectedProtocol(SSLSocket socket) {
        if (!sslSocketClass.isInstance(socket)) {
            return "";
        }
        try {
            byte[] alpnResult = (byte[]) getAlpnSelectedProtocol.invoke(socket);
            return alpnResult != null ? new String(alpnResult, UTF_8) : null;
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new AssertionError(e);
        }
    }

    @Override
    public void log(int level, String message, @Nullable Throwable t) {
    }

    @Override
    public @Nullable
    Object getStackTraceForCloseable(String closer) {
        return closeGuard.createAndOpen(closer);
    }

    @Override
    public void logCloseableLeak(String message, Object stackTrace) {
        boolean reported = closeGuard.warnIfOpen(stackTrace);
        if (!reported) {
            log(WARN, message, null);
        }
    }

    @Override
    public boolean isCleartextTrafficPermitted(String hostname) {
        try {
            Class<?> networkPolicyClass = Class.forName("android.security.NetworkSecurityPolicy");
            Method getInstanceMethod = networkPolicyClass.getMethod("getInstance");
            Object networkSecurityPolicy = getInstanceMethod.invoke(null);
            return api24IsCleartextTrafficPermitted(hostname, networkPolicyClass, networkSecurityPolicy);
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            return super.isCleartextTrafficPermitted(hostname);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new AssertionError("unable to determine cleartext support", e);
        }
    }

    private boolean api24IsCleartextTrafficPermitted(String hostname, Class<?> networkPolicyClass,
                                                     Object networkSecurityPolicy) throws InvocationTargetException, IllegalAccessException {
        try {
            Method isCleartextTrafficPermittedMethod = networkPolicyClass
                    .getMethod("isCleartextTrafficPermitted", String.class);
            return (boolean) isCleartextTrafficPermittedMethod.invoke(networkSecurityPolicy, hostname);
        } catch (NoSuchMethodException e) {
            return api23IsCleartextTrafficPermitted(hostname, networkPolicyClass, networkSecurityPolicy);
        }
    }

    private boolean api23IsCleartextTrafficPermitted(String hostname, Class<?> networkPolicyClass,
                                                     Object networkSecurityPolicy) throws InvocationTargetException, IllegalAccessException {
        try {
            Method isCleartextTrafficPermittedMethod = networkPolicyClass
                    .getMethod("isCleartextTrafficPermitted");
            return (boolean) isCleartextTrafficPermittedMethod.invoke(networkSecurityPolicy);
        } catch (NoSuchMethodException e) {
            return super.isCleartextTrafficPermitted(hostname);
        }
    }

    public CertificateChainCleaner buildCertificateChainCleaner(X509TrustManager trustManager) {
        try {
            Class<?> extensionsClass = Class.forName("android.net.http.X509TrustManagerExtensions");
            Constructor<?> constructor = extensionsClass.getConstructor(X509TrustManager.class);
            Object extensions = constructor.newInstance(trustManager);
            Method checkServerTrusted = extensionsClass.getMethod(
                    "checkServerTrusted", X509Certificate[].class, String.class, String.class);
            return new OhosCertificateChainCleaner(extensions, checkServerTrusted);
        } catch (InstantiationException e) {
            e.fillInStackTrace();
        } catch (InvocationTargetException e) {
            e.fillInStackTrace();
        } catch (NoSuchMethodException e) {
            e.fillInStackTrace();
        } catch (IllegalAccessException e) {
            e.fillInStackTrace();
        } catch (ClassNotFoundException e) {
            e.fillInStackTrace();
        }
        return null;
    }

    public static @Nullable
    Platform buildIfSupported() {
        if (!Platform.isOhos()) {
            return null;
        }

        Class<?> sslParametersClass = null;
        Class<?> sslSocketClass = null;

        try {
            sslParametersClass = Class.forName("com.android.org.conscrypt.SSLParametersImpl");
            sslSocketClass = Class.forName("com.android.org.conscrypt.OpenSSLSocketImpl");
        } catch (ClassNotFoundException ignored) {
            ignored.fillInStackTrace();
        }
        try {
            Method setUseSessionTickets = sslSocketClass.getDeclaredMethod(
                    "setUseSessionTickets", boolean.class);
            Method setHostname = sslSocketClass.getMethod("setHostname", String.class);
            Method getAlpnSelectedProtocol = sslSocketClass.getMethod("getAlpnSelectedProtocol");
            Method setAlpnProtocols = sslSocketClass.getMethod("setAlpnProtocols", byte[].class);
            return new OhosPlatform(sslParametersClass, sslSocketClass, setUseSessionTickets,
                    setHostname, getAlpnSelectedProtocol, setAlpnProtocols);
        } catch (NoSuchMethodException ignored) {
            ignored.fillInStackTrace();
        }
        throw new IllegalStateException(
                "Expected ohos API level 21+ but was ");
    }

    @Override
    public TrustRootIndex buildTrustRootIndex(X509TrustManager trustManager) {
        try {
            Method method = trustManager.getClass().getDeclaredMethod(
                    "findTrustAnchorByIssuerAndSignature", X509Certificate.class);
            method.setAccessible(true);
            return new CustomTrustRootIndex(trustManager, method);
        } catch (NoSuchMethodException e) {
            return super.buildTrustRootIndex(trustManager);
        }
    }

    static final class OhosCertificateChainCleaner extends CertificateChainCleaner {
        private final Object x509TrustManagerExtensions;
        private final Method checkServerTrusted;

        OhosCertificateChainCleaner(Object x509TrustManagerExtensions, Method checkServerTrusted) {
            this.x509TrustManagerExtensions = x509TrustManagerExtensions;
            this.checkServerTrusted = checkServerTrusted;
        }

        @Override
        public List<Certificate> clean(List<Certificate> chain, String hostname)
                throws SSLPeerUnverifiedException {
            try {
                X509Certificate[] certificates = chain.toArray(new X509Certificate[chain.size()]);
                return (List<Certificate>) checkServerTrusted.invoke(
                        x509TrustManagerExtensions, certificates, "RSA", hostname);
            } catch (InvocationTargetException e) {
                SSLPeerUnverifiedException exception = new SSLPeerUnverifiedException(e.getMessage());
                exception.initCause(e);
                throw exception;
            } catch (IllegalAccessException e) {
                throw new AssertionError(e);
            }
        }

        @Override
        public boolean equals(Object other) {
            return other instanceof OhosCertificateChainCleaner; // All instances are equivalent.
        }

        @Override
        public int hashCode() {
            return 0;
        }
    }
    static final class CloseGuard {
        private final Method getMethod;
        private final Method openMethod;
        private final Method warnIfOpenMethod;

        CloseGuard(Method getMethod, Method openMethod, Method warnIfOpenMethod) {
            this.getMethod = getMethod;
            this.openMethod = openMethod;
            this.warnIfOpenMethod = warnIfOpenMethod;
        }

        Object createAndOpen(String closer) {
            if (getMethod != null) {
                try {
                    Object closeGuardInstance = null;
                    try {
                        closeGuardInstance = getMethod.invoke(null);
                    } catch (IllegalAccessException e) {
                        e.fillInStackTrace();
                    } catch (InvocationTargetException e) {
                        e.fillInStackTrace();
                    }
                    try {
                        openMethod.invoke(closeGuardInstance, closer);
                    } catch (IllegalAccessException e) {
                        e.fillInStackTrace();
                    } catch (InvocationTargetException e) {
                        e.fillInStackTrace();
                    }
                    return closeGuardInstance;
                } catch (IllegalArgumentException e) {
                    e.fillInStackTrace();
                }
            }
            return Collections.emptyList();
        }

        boolean warnIfOpen(Object closeGuardInstance) {
            boolean reported = false;
            if (closeGuardInstance != null) {
                try {
                    try {
                        warnIfOpenMethod.invoke(closeGuardInstance);
                    } catch (IllegalAccessException e) {
                        e.fillInStackTrace();
                    } catch (InvocationTargetException e) {
                        e.fillInStackTrace();
                    }
                    reported = true;
                } catch (IllegalArgumentException e) {
                    e.fillInStackTrace();
                }
            }
            return reported;
        }

        static CloseGuard get() {
            Method getMethod;
            Method openMethod;
            Method warnIfOpenMethod;

            try {
                Class<?> closeGuardClass = Class.forName("dalvik.system.CloseGuard");
                getMethod = closeGuardClass.getMethod("get");
                openMethod = closeGuardClass.getMethod("open", String.class);
                warnIfOpenMethod = closeGuardClass.getMethod("warnIfOpen");
            } catch (Exception ignored) {
                getMethod = null;
                openMethod = null;
                warnIfOpenMethod = null;
            }
            return new CloseGuard(getMethod, openMethod, warnIfOpenMethod);
        }
    }
    static final class CustomTrustRootIndex implements TrustRootIndex {
        private final X509TrustManager trustManager;
        private final Method findByIssuerAndSignatureMethod;

        CustomTrustRootIndex(X509TrustManager trustManager, Method findByIssuerAndSignatureMethod) {
            this.findByIssuerAndSignatureMethod = findByIssuerAndSignatureMethod;
            this.trustManager = trustManager;
        }

        @Override
        public X509Certificate findByIssuerAndSignature(X509Certificate cert) {
            try {
                TrustAnchor trustAnchor = (TrustAnchor) findByIssuerAndSignatureMethod.invoke(
                        trustManager, cert);
                return trustAnchor != null
                        ? trustAnchor.getTrustedCert()
                        : null;
            } catch (IllegalAccessException e) {
                throw new AssertionError("unable to get issues and signature", e);
            } catch (InvocationTargetException e) {
                return null;
            }
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (!(obj instanceof CustomTrustRootIndex)) {
                return false;
            }
            CustomTrustRootIndex that = (CustomTrustRootIndex) obj;
            return trustManager.equals(that.trustManager)
                    && findByIssuerAndSignatureMethod.equals(that.findByIssuerAndSignatureMethod);
        }

        @Override
        public int hashCode() {
            return trustManager.hashCode() + 31 * findByIssuerAndSignatureMethod.hashCode();
        }
    }

    @Override
    public SSLContext getSSLContext() {
        boolean tryTls12 = true;
        if (tryTls12) {
            try {
                return SSLContext.getInstance("TLSv1.2");
            } catch (NoSuchAlgorithmException e) {
                e.fillInStackTrace();
            }
        }
        try {
            return SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("No TLS provider", e);
        }
    }

}
